#!/usr/bin/php
<?php
/**
 * Tool for gather code style checker 
 * statistics and post it to code.google.com
 * 
 * @category Hydrum
 * @package Hydrum
 * @subpackage Tools
 * @author kamenskiy.v@gmail.com 
 */

if (!isset($_SERVER['argv'][1])) {
    echo "Error: Please provide path to repositories." . PHP_EOL;
    exit;
}

define('SOURCE_CODE_PATH', $_SERVER['argv'][1] . 'hydrum/source/');
define('BROWSE_CODE_URL', 'http://code.google.com/p/hydrum/source/browse/source/');
define('WIKI_PATH', $_SERVER['argv'][1] . 'wiki.hydrum/');
define('WIKI_PAGE', 'CodingStyleWarnings.wiki'); 

$output = shell_exec('phpcs --standard=Zend --report=xml ' . SOURCE_CODE_PATH);

$xml = simplexml_load_string($output);

$codeStyleWarningsWiki = '';

foreach ($xml as $file)
{
    $fileURL = str_replace(SOURCE_CODE_PATH, BROWSE_CODE_URL, $file['name']);
    $codeStyleWarningsWiki .= 
        '==' . basename($file['name']) . '==' . PHP_EOL .
        '_Browse Code:_ [' . $fileURL. ' click here]';
        
    $codeStyleWarningsWiki .= renderWikiTable($file->error, 'Errors');   
    $codeStyleWarningsWiki .= renderWikiTable($file->warning, 'Warnings');   
}

chdir(WIKI_PATH);

shell_exec('hg pull');
shell_exec('hg update');

file_put_contents(WIKI_PATH . WIKI_PAGE, $codeStyleWarningsWiki);

shell_exec('hg commit --user="Code Style Checker" --message="Updating list of warnings" ');
shell_exec('hg push');

function renderWikiTable($records, $label)
{
    $table = '';
    
    if (count($records) > 0)
    {
        $table .= 
            PHP_EOL . PHP_EOL . '_Found ' . $label . '_: ' . count($records) . PHP_EOL;
    
        $table .= 
            '|| *Line* || *Column* || *Description* ||' . PHP_EOL;
        
        foreach ($records as $record) {
        
            $table .=
                '|| ' .$record['line']. ' || ' . $record['line'] . ' || ' . $record[0] . ' ||' . PHP_EOL;
        }
        
        $table .= PHP_EOL . PHP_EOL;        
    }
    
    return $table;
}
